import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { 
  BlogFile, 
  FileUploadResponse, 
  SignedUrlResponse,
  ApiResponse 
} from '../models/blog.model';
import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root'
})
export class FileService {
  private readonly BASE_URL = 'http://localhost:8000/api/v1';
  private http = inject(HttpClient);
  private authService = inject(AuthService);

  /**
   * 上传文件
   */
  uploadFile(file: File): Observable<FileUploadResponse> {
    const formData = new FormData();
    formData.append('image', file);

    return this.http.post<FileUploadResponse>(`${this.BASE_URL}/file/upload`, formData, {
      headers: this.getAuthHeadersForUpload()
    });
  }

  /**
   * 获取文件签名URL
   */
  getSignedUrl(key: string): Observable<SignedUrlResponse> {
    let httpParams = new HttpParams();
    httpParams = httpParams.set('key', key);

    return this.http.get<SignedUrlResponse>(`${this.BASE_URL}/file/signed-url`, {
      params: httpParams,
      headers: this.getAuthHeaders()
    });
  }

  /**
   * 删除文件
   */
  deleteFile(key: string): Observable<ApiResponse> {
    let httpParams = new HttpParams();
    httpParams = httpParams.set('key', key);

    return this.http.delete<ApiResponse>(`${this.BASE_URL}/file/delete-file`, {
      params: httpParams,
      headers: this.getAuthHeaders()
    });
  }

  /**
   * 获取认证请求头（用于上传文件，不设置Content-Type）
   */
  private getAuthHeadersForUpload(): HttpHeaders {
    const token = this.authService.getToken();
    return new HttpHeaders({
      'Authorization': `Bearer ${token}`
    });
  }

  /**
   * 获取认证请求头
   */
  private getAuthHeaders(): HttpHeaders {
    const token = this.authService.getToken();
    return new HttpHeaders({
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    });
  }
} 